using UnityEditor;
using UnityEngine;
using System.IO;
using System.Collections.Generic;
using ExcelSpace;

public class ExcelEditorWindow : EditorWindow
{
    private string searchQuery = "";
    private List<SheetInfo> excelFiles = new List<SheetInfo>();


    [MenuItem("Tools/Excel 工具窗口")]
    public static void ShowWindow()
    {
        GetWindow<ExcelEditorWindow>("Excel 工具窗口");
    }

    private void OnEnable()
    {
        // 加载所有 Excel 文件
        LoadExcelFiles();
    }

    private void OnGUI()
    {
        GUILayout.Label("Excel 文件管理器", EditorStyles.boldLabel);

        if (GUILayout.Button("重载所有Excel文件"))
        {
            string[] xlsFiles = Directory.GetFiles(Application.dataPath + "/Editor/Excel", "*.xlsx", SearchOption.AllDirectories);
            foreach (var item in xlsFiles)
            {
                int index = item.IndexOf("Assets");
                string file = item.Substring(index);
                AssetDatabase.ImportAsset(file, ImportAssetOptions.Default);
            }
        }
        GUILayout.Space(10);

        // 搜索框
        GUILayout.BeginHorizontal();
        GUILayout.Label("查询表格:", GUILayout.Width(60));
        searchQuery = GUILayout.TextField(searchQuery);
        GUILayout.EndHorizontal();

        // 显示表格文件列表
        DisplayExcelFiles();
    }

    private void LoadExcelFiles()
    {
        // 清空之前的列表
        excelFiles.Clear();

        // 获取所有 Excel 文件
        string[] files = Directory.GetFiles("Assets/Editor/Excel", "*.xlsx", SearchOption.AllDirectories);
        foreach (var file in files)
        {
            excelFiles.Add(new SheetInfo(file));
        }
    }

    private void DisplayExcelFiles()
    {
        // 如果有搜索关键字，进行过滤
        var filteredFiles = excelFiles.FindAll(file => string.IsNullOrEmpty(searchQuery) || file.fullName.ToLower().Contains(searchQuery.ToLower()));

        // 显示文件列表
        foreach (var file in filteredFiles)
        {
            if (GUILayout.Button($"{file.chineseName} - {file.englishName}"))
            {
                Tools.Run(file.filePath);
            }
        }
    }
}
